package common.security.web.util;

import java.util.Collection;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import common.security.User;

public class SecurityUtil {

	/**
	 * 判断是否包含权限
	 * 
	 * @param authName
	 * @return
	 */
	public static boolean contains(String authName) {
		SimpleGrantedAuthority auth = new SimpleGrantedAuthority(authName);
		return getAuthentication().getAuthorities().contains(auth);
	}

	public static Authentication getAuthentication() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		return authentication;
	}

	/**
	 * 获取用户所有权限
	 * 
	 * @return
	 */
	public static Collection<? extends GrantedAuthority> getAuthorities() {
		return getAuthentication().getAuthorities();
	}

	public static Object getUserDetails() {
		Authentication authentication = getAuthentication();
		return authentication.getPrincipal();

	}

	public static String getUserId() {
		Object us = getUserDetails();
		if (us instanceof User) {
			return ((User) us).getId();
		}
		return us.toString();
	}
	public static boolean isAdmin() {
		Object us = getUserDetails();
		if (us instanceof User) {
			return ((User) us).isAdmin();
		}
		return false;
	}

	public static String getUserName() {
		Object us = getUserDetails();
		if (us instanceof User) {
			return ((User) us).getUsername();
		}
		return us.toString();
	}

	public static String getUserIp() {
		Authentication authentication = getAuthentication();
		Object details = authentication.getDetails();
		if(details instanceof WebAuthenticationDetails) {
			return ((WebAuthenticationDetails) details).getRemoteAddress();
		}
		return "0.0.0.0";
	}
	

}
